import React, {Component} from 'react';
import {
    ActivityIndicator,
    Alert,
    FlatList,
    Image,
    RefreshControl,
    StyleSheet,
    Text,
    TextInput,
    TouchableOpacity,
    View,
} from 'react-native';
import SelfadaptModal from 'react-native-selfadapt-modal';
import axiosInstance from '../utils/request';
import RNDateTimePicker ,{DateTimePickerAndroid} from '@react-native-community/datetimepicker';
import getStyles from '../../style/styles';



let rows=20;//
let totalPage=0;//总的页数
let itemNo=0;//item的个数

const menuItem = [
    {flag:'last',name:'接上次抄表'},
    {flag:'first',name:'从第一户抄表'},
    {flag:'order',name:'按顺序抄表'},
];


let styles={};
export default class MeterBook extends Component {


    constructor(props){
        super(props);
        this.state = {
            page:1,
            isLoading: true,
            //网络请求状态
            dataArray: [],
            error: false,
            errorInfo: "",
            tabIndex:1,
            currMonth:new Date(),
            showDatePicker:false,
            modalVisible: false,//模态场景是否可见
        };
        this.refreshList = null

    }

    //组件挂载完成后执行的方法
    componentDidMount(){
        this.refreshList && this.refreshList.handleRefresh()
        this.fetchData('')
    }

    /*
		因为服务端modified字段代表的是时间戳，所以Max(anchor)表示客户端最近一次同步的时间，如果存在服务端modified > Max(anchor),
		说明服务端需要向客户端同步数据。
	*/
    fetchData(bookName){
        let URL= global.server.url+'/meterBooks/selectListPage';
        if(bookName){
            page=1;
        }else{
            page=this.state.page;
        }
        axiosInstance.post(URL,
            {
                bookName:bookName,
                pageVO:{
                    page:page,
                    rows:rows
                }
            }
        )
            .then(res => {
                let datas = [];
                let list=res.list;
                let count=list.records.length;
                totalPage=list.pages;
                datas = datas.concat(list.records);
                let dataBlob = [];//这是创建该数组，目的放存在key值的数据，就不会报黄灯了
                let i = itemNo;
                datas.map(function (item) {
                    dataBlob.push({
                        key: i,
                        bookId:item.id,
                        bookNo: item.bookNo,
                        bookName: item.bookName,
                        custNumber:item.custNumber
                    })
                    i++;
                });
                itemNo = i;
                let foot = 0;
                if(this.state.page>=totalPage){
                    foot = 1;//listView底部显示没有更多数据了
                }

                this.setState({
                    //复制数据源
                    //  dataArray:this.state.dataArray.concat( responseData.results),
                    dataArray:this.state.dataArray.concat(dataBlob),
                    isLoading: false,
                    showFoot:foot,
                    isRefreshing:false,
                    count:count
                });
                datas = null;//重置为空
                dataBlob = null;
            })
            .catch(error => {
                this.setState({
                    error: true,
                    errorInfo: error
                });
                Alert.alert("网络异常，请稍后再试！");
            })
    }


    handleRefresh = () => {
        this.setState({
            page:1,
            isRefreshing:true,//tag,下拉刷新中，加载完全，就设置成flase
            dataArray:[]
        });
        this.fetchData()
    }




    searchData(){
        let bookName=this.state.bookName;
        this.setState({
            dataArray:[]
        });
        this.fetchData(bookName);
    }

    _onChangeText(text) {
        if (text) {
            this.setState({
                bookName: text,
                dataArray:[]
            })  //实时变化值
            clearTimeout(this.settimeId);       //如搜索的内容变化在1秒之中，可以清除变化前的fetch请求，继而减少fetch请求。但不能中断fetch请求
            this.settimeId = setTimeout(() => {
                this.fetchData(text);
            }, 1000);                                      //让每次要进行fetch请求时先延迟1秒在进行
            console.log("sheng chen id:" + this.settimeId);
        } else {
            this.setState({bookName: '' })
        }
    }

    doSelect = (value,item) => {
        if(value.flag=='order'){//如果是按顺序抄表，则跳转到CostMasterScene
            this.props.navigation.navigate('CostMasterScene', {bookId:item.bookId,bookName:item.bookName});
        }else{
            this.props.navigation.navigate('Entry', {bookId:item.bookId,flag:value.flag});
        }
    }

    renderItem = ({item})=>{
        return (
            <TouchableOpacity activeOpacity={0.5}  onPress={() => this.doSelect({'flag':'last'},item)}>
                <View style={style.oneBox}>
                    <SelfadaptModal
                        menuList={menuItem}
                        containerStyle={style.oneBtn}
                        content={this.state.selectMenu}
                        onPress={(res)=>this.doSelect(res,item)}>
                        <Image style={{marginTop: 5,marginLeft:8, width:20,height:20}} source={require('../../img/arrow06.png')} />
                    </SelfadaptModal>
                    <Text style={styles.listItem}>{item.bookName}[{item.bookNo}]</Text>
                </View>
            </TouchableOpacity>
        )
    }

    renderData() {
        styles=getStyles();
        return (
            <View style={style.container} >
                <View style={{ paddingRight: 15, paddingLeft: 15, marginTop: 10 }}>
                    <View style={{ height: 40, backgroundColor: "#fff", borderRadius: 10, paddingLeft: 25, flexDirection: 'row', alignItems: 'center' }} >
                        <Image source={require('../../img/search.png')} style={{ width: 25, height: 20 }}></Image>
                        <TextInput underlineColorAndroid="transparent" placeholder="请输入表册名称并点击搜索" style={{ marginLeft: 10, width: 200 }}
                                   onChangeText={this._onChangeText.bind(this)}
                                   value={this.state.bookName}
                                   ref={this.keyWordInput}
                                   onSubmitEditing={() => { this.keyWordInput.blur() }}>
                        </TextInput>
                        <TouchableOpacity onPress={this.searchData.bind(this)} style={styles.searchView}>
                            <Text style={{ color: '#0391ff', fontSize: 14 }}>搜索</Text>
                        </TouchableOpacity>
                    </View>
                </View>

                <FlatList
                    data={this.state.dataArray}
                    renderItem = {this.renderItem.bind(this)}
                    ListFooterComponent={this._renderFooter.bind(this)}
                    onEndReached={this._onEndReached.bind(this)}
                    onEndReachedThreshold={0.1}
                    ItemSeparatorComponent={this._separator}
                    keyExtractor={this._keyExtractor}
                    windowSize={300}
                    //为刷新设置颜色
                    refreshControl={
                        <RefreshControl
                            refreshing={this.state.isRefreshing}
                            onRefresh={this.handleRefresh.bind(this)}//因为涉及到this.state
                            colors={['#ff0000', '#00ff00','#0000ff','#3ad564']}
                            progressBackgroundColor="#ffffff"
                        />
                    }
                />

                <View style={{
                    height:30,
                    justifyContent:'space-between',
                    flexDirection:'row',
                    alignItems:'center',
                    borderBottomWidth:1,
                    borderBottomColor:'#D7D7D7',
                    backgroundColor:"#F5FCFF",
                    paddingLeft:6
                }}>
                    <Text style={[styles.headerText,{textAlign:'left'}]} onPress={()=>{
                        this.setState({showDatePicker:true})
                    }}>日历</Text>

                    {
                        this.state.showDatePicker && (
                            <RNDateTimePicker
                                style={{width: 120}}
                                value={this.state.currMonth}
                                mode="date"
                                placeholder="select date"
                                androidMode="spinner"
                                format="YYYY-MM"
                                minDate={global.user.accountCycle.currMonth}
                                maxDate={global.user.accountCycle.currMonth}
                                confirmBtnText="Confirm"
                                cancelBtnText="Cancel"
                                customStyles={{
                                    dateIcon: {
                                        position: 'absolute',
                                        left: 0,
                                        top: 4,
                                        marginLeft: 0
                                    },
                                    dateInput: {
                                        marginLeft: 36,
                                        borderWidth:0
                                    }
                                }}
                                onDateChange={(date) => {this.setState({currMonth: date,showDatePicker:false})}}
                            />
                        )
                    }

                    <Text style={styles.headerText}>表册数：{this.state.count}</Text>
                </View>
            </View>
        );
    }

    render() {
        //第一次加载等待的view
        if (this.state.isLoading && !this.state.error) {
            return this.renderLoadingView();
        } else if (this.state.error) {
            //请求失败view
            return this.renderErrorView();
        }
        //加载数据
        return this.renderData();
    }

    _separator(){
        return <View style={{height:1,backgroundColor:'#999999'}}/>;
    }

    //加载失败view
    renderErrorView() {
        return (
            <View style={styles.container}>
                <Text>
                    {this.state.errorInfo}
                </Text>
            </View>
        );
    }

    //加载等待页
    renderLoadingView() {
        return (
            <View style={styles.container}>
                <ActivityIndicator
                    animating={true}
                    color='blue'
                    size="large"
                />
            </View>
        );
    }

    _separator(){
        return <View style={{height:1,backgroundColor:'#999999'}}/>;
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    <ActivityIndicator />
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    _onEndReached(){
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot != 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((this.state.page!=1) && (this.state.page>=totalPage)){
            return;
        } else {
            this.state.page++;
        }
        //底部显示正在加载更多数据
        this.setState({showFoot:2});
        //获取数据，在componentDidMount()已经请求过数据了
        if (this.state.page>1){
            this.fetchData();
        }
    }

}

const style = StyleSheet.create({
    container: {
        flex: 1
    },
    flexCenter: {
        flex: 1,alignItems: 'center',justifyContent:'center'
    },
    oneBtn: {
        padding: 5,
        borderRadius: 5,
    },
    oneBox: {
        flexDirection: 'row',
        alignItems: 'center',
    },
});
